package com.ytrsoft.controller;

import com.ytrsoft.entity.BaseEntity;
import com.ytrsoft.response.ResponseEntity;
import com.ytrsoft.service.BaseService;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

public abstract class BaseRestController<T extends BaseEntity> {

    protected final BaseService<T> baseService;

    public BaseRestController(BaseService<T> baseService) {
        this.baseService = baseService;
    }

    @PostMapping
    @Operation(summary = "创建")
    public ResponseEntity<T> create(@RequestBody T entity) {
        T createdEntity = baseService.create(entity);
        return ResponseEntity.succeed(createdEntity);
    }

    @GetMapping("/{id}")
    @Operation(summary = "根据ID查询")
    public ResponseEntity<T> findById(@PathVariable String id) {
        T instance = baseService.findById(id);
        return ResponseEntity.succeed(instance);
    }

    @GetMapping
    @Operation(summary = "分页查询")
    public ResponseEntity<Page<T>> findAll(Pageable pageable) {
        Page<T> page = baseService.findAll(pageable);
        return ResponseEntity.succeed(page);
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新")
    public ResponseEntity<T> update(@PathVariable String id, @RequestBody T entity) {
        entity.setId(id);
        T updatedEntity = baseService.update(entity);
        return ResponseEntity.succeed(updatedEntity);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除")
    public ResponseEntity<T> delete(@PathVariable String id) {
        T deletedEntity = baseService.delete(id);
        return ResponseEntity.succeed(deletedEntity);
    }
}
